<template>
	<base-loading-box
		class="flex-1"
		:isEmpty="!data && isEmpty"
		:loading="!data && loading"
		:error="error">
		<template v-if="data">
			<base-card
				v-for="market in data.markets"
				:key="market.marketId"
				:title="market.marketTypeName"
				collapsible
				collapse
				class="mt-2">
				<betting-select :match="data" :market="market"></betting-select>
			</base-card>
		</template>
	</base-loading-box>
</template>

<script lang="ts" setup>
import { BaseCard, BaseLoadingBox } from '@/components/base'
import { BettingSelect } from '@/components/betting'
import { computed, onBeforeUnmount, watch } from 'vue'
import { getMatchMore } from '@/api/betting'
import { useRequest } from '@/hooks'
import { useAppStore, useMatchStore } from '@/store'
import { Match } from '@/types'

const props = defineProps({
	eventId: {
		type: String
	}
})

const appStore = useAppStore()
const matchStore = useMatchStore()

const params = computed(() => ({
	location: appStore.region,
	locale: appStore.lang,
	oddsStyle: appStore.odds,
	eventId: props.eventId
}))

let timer: any

const { run, data, loading, error, isEmpty } = useRequest<Match>(getMatchMore, {
	onSuccess: () => {
		if (props.eventId && data.value) {
			matchStore.matchData[props.eventId] = data.value
		}
	},
	onFinally: () => {
		timer && clearTimeout(timer)
		timer = setTimeout(() => run(params.value), 10000)
	}
})

watch(
	() => params.value,
	() => {
		timer && clearTimeout(timer)
		run(params.value)
	},
	{ immediate: true }
)

onBeforeUnmount(() => {
	timer && clearTimeout(timer)
})
</script>
